package tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

public class SEOTask implements Runnable {
	private List<URL> addresses;
	private static final int ROTATION_BREAK = 15000;
	private static final String TEST_URL = "http://www.yibeicoffee.com";
	
	public SEOTask(File file) {
		addresses = new ArrayList<URL>();
		try {
			addresses.add(new URL(TEST_URL));
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(file!=null && file.exists()) {
			try {
				Scanner s = new Scanner(file);
				while(s.hasNextLine()) {
					String line = s.nextLine();
					try {
						URL addr = new URL(line);
						addresses.add(addr);
					} catch (MalformedURLException e) {
						System.err.println("malformed url ignored: " + line);
					}
				}
			} catch (FileNotFoundException e) {
				throw new RuntimeException("This should never occur", e);
			}	
		}
	}
	
	public void visitAll() {
		for(URL addr : addresses) {
			// System.out.println("Visiting address : " + addr.toString());
			this.visit(addr);
		}
	}
	
	public void visit(URL addr) {
		URLConnection conn = null;
		BufferedReader in = null;
		try {
			 conn = addr.openConnection();
			 conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; pl-PL; rv:2.0) Gecko/20110307 Firefox/4.0");
			 conn.setRequestProperty("Referer", "http://www.bing.com/search?q=cbu+%E7%A4%BE%E5%8C%BA&go=&form=QBLH&filt=all&qs=n&sk=");
			 conn.setRequestProperty("Connection", "keep-alive");
			 conn.setRequestProperty("Accept", "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
			 conn.setRequestProperty("Host", addr.getHost());
			 // system
			 
			 in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			 String line = null;
			 while(null != (line = in.readLine())) {
				 // System.out.println(line);
			 }
			 
		} catch (IOException e) {
			System.out.println(new Date() + " IOException Occured " + e.getMessage());
			e.printStackTrace();
		} finally {
			try {
				conn.getInputStream().close();
				in.close();
			} catch (Throwable ignore) {}
		}
	}
	
	public static void main(String[] args) {
		Thread t = new Thread(new SEOTask(null));
		t.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true) {
			this.visitAll();
			try {
				Thread.sleep(ROTATION_BREAK);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
